package cn.spy.threaddownload.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    /**
     * 获取url连接HttpURLConnection
     *
     * @param fileUrl
     * @return
     */
    public static HttpURLConnection getUrlConnection(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            return (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void downloadByUrl(String fileUrl, String destPath) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream is = connection.getInputStream();
        downloadByUrl(is, destPath, connection.getContentLength());
        is.close();
        connection.disconnect();
    }

    public static void downloadByUrl(InputStream is, String destPath, int contentLength) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(destPath,"rw");
        byte[] dataArr = new byte[contentLength];
        int len = 0;
        while ((len = is.read(dataArr)) != -1) {
            raf.write(dataArr, 0 , len);
        }

        raf.close();
    }
}
